<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="问卷填写">
        <el-row>
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  v-if="showClose === false"
              label-width="68px">
              <el-form-item label="问卷名称" prop="questionnaireName">
                <el-input v-model="queryParams.questionnaireName" placeholder="请输入问卷名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="活动时间" prop="initiationTime">
                <el-date-picker clearable v-model="queryParams.initStartTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                  placeholder="请选择开始时间">
                </el-date-picker>
                至
                <el-date-picker clearable v-model="queryParams.initEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                  placeholder="请选择结束时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
            <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
            <el-table :row-style="{ height: '30px' }" :cell-style="{ padding: '0px' }" height="450" border
              v-loading="loading" :data="trainingList" highlight-current-row>
              <el-table-column label="序号" type="index" :index="indexMethod" />
              <el-table-column label="状态" align="center" prop="status" v-if="columns[0].visible" />
              <el-table-column label="问卷名称" align="center" prop="questionnaireName" v-if="columns[1].visible"
                :show-overflow-tooltip="true">
              </el-table-column>
              <el-table-column label="第三方网址" align="center" prop="thirdPartyUrl" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <template>
                    <!-- 使用按钮作为可点击元素，并绑定点击事件 -->
                    <el-button @click="handleClick(scope.row.thirdPartyUrl)" type="text">
                      {{ scope.row.thirdPartyUrl }}
                    </el-button>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="发起单位" align="center" prop="initiateUnits" v-if="columns[2].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="发起时间" align="center" prop="initiateTime" width="120" v-if="columns[3].visible">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.initiateTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="联系人" align="center" prop="contacts" v-if="columns[4].visible" />
              <el-table-column label="联系方式" align="center" prop="telephone" v-if="columns[5].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="开始时间" align="center" prop="startTime" width="120" v-if="columns[6].visible">
                <template slot-scope="scope">
                  <span>{{ parseUTCTime(scope.row.startTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" prop="endTime" width="120" v-if="columns[7].visible">
                <template slot-scope="scope">
                  <span>{{ parseUTCTime(scope.row.endTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="附件" align="center" prop="fileUrl" v-if="columns[10].visible">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.fileUrl != null && scope.row.fileUrl != ''"
                    @click.stop="handlePictureCardPreview(scope.row.fileUpload)" size="small" type="text">附件</el-button>
                  <el-button size="small" v-else type="text">无附件</el-button>
                </template>
                <!--            <template slot-scope="scope">-->
                <!--              &lt;!&ndash; 表格中的 &ndash;&gt;-->
                <!--              <el-image-->
                <!--                slot="reference"-->
                <!--                v-if="scope.row.fileUrl!=null"-->
                <!--                :src="scope.row.fileUrl"-->
                <!--                style="width:7rem;height:4rem;"-->
                <!--              />-->
                <!--            </template>-->
              </el-table-column>
              <el-table-column label="作答人" align="center" prop="answerUser" v-if="columns[13].visible"
                :show-overflow-tooltip="true" />
              <el-table-column v-if="enterpriseId === null" label="操作" align="center"
                class-name="small-padding fixed-width" width="100px">
                <template slot-scope="scope">
                  <el-button
                    :disabled="!(scope.row.isAnswer === 0 && scope.row.questionnaireType !== '第三方' && isCurrentTimeBeforeEndTime(scope.row.startTime, scope.row.endTime) && scope.row.status !== '结束')"
                    size="mini" type="text" icon="el-icon-postcard"
                    @click="handleAnswer(scope.row, scope.$index)" title="填写问卷"></el-button>
                  <el-button v-if="scope.row.isAnswer !== 0 && scope.row.questionnaireType !== '第三方'" size="mini"
                    type="text" icon="el-icon-copy-document"
                    @click="handleSelectAnswer(scope.row, scope.$index)" title="查看答卷"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>
          </el-col>

        </el-row>
        <!-- 添加或修改活动信息培训对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="closeTrain">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
                <div v-if="addSign !== 0">
                  <el-descriptions title="">
                    <el-descriptions-item label="序号">
                      <el-tag size="medium">{{ form.index }}</el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
                <el-form-item label="主分类" prop="administrativeArea">
                  <treeselect v-model="form.classificationId" :options="options" placeholder="请选择主分类"
                    v-if="opt != 'details'" style="width: 202.5px" :disabled="ReadOnly" />
                  <el-input v-else v-model="form.label" placeholder="行政区域" />
                </el-form-item>
                <el-form-item label="创建人" prop="creationName">
                  <el-input v-model="form.creationName" placeholder="请输入创建人" disabled="true" />
                </el-form-item>
                <el-form-item label="创建时间" prop="creationTime">
                  <el-date-picker clearable v-model="form.creationTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择创建时间" style="width: 202.5px" disabled="true">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="问卷类型" prop="questionnaireType">
                  <el-select v-model="form.questionnaireType" placeholder="请选择形式" style="width: 202.5px"
                    :disabled="ReadOnly">
                    <el-option label="自定义" value="自定义"></el-option>
                    <el-option label="第三方" value="第三方"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="问卷名称" prop="questionnaireName">
                  <el-input v-model="form.questionnaireName" placeholder="请输入问卷名称" :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="发起单位" prop="initiateUnits">
                  <el-input v-model="form.initiateUnits" placeholder="请输入发起单位" :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="发起时间" prop="initiateTime">
                  <el-date-picker clearable v-model="form.initiateTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择发起时间" style="width: 202.5px" :disabled="ReadOnly">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker clearable v-model="form.startTime" type="datetime"  value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择开始时间" style="width: 202.5px" :disabled="ReadOnly">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker clearable v-model="form.endTime" type="datetime"  value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择结束时间" style="width: 202.5px" :disabled="ReadOnly">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="联系人" prop="contacts">
                  <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="联系电话" prop="telephone">
                  <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="审核人" prop="examineName">
                  <el-input v-model="form.examineName" placeholder="请选择审核人" @focus="selectOpen(0)"
                    :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="发送方式" prop="sendType">
                  <el-radio-group v-model="form.sendType" :disabled="ReadOnly">
                    <el-radio label="oneClick">一键发送</el-radio>
                    <el-radio label="groupSend">分类群发</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="form.sendType === 'groupSend'" label="群发内容" prop="receiverName">
                  <el-input v-model="form.receiverName" type="textarea" placeholder="请输入内容" style="width: 500px"
                    @focus="handleTextAreaFocus" :disabled="ReadOnly" />
                </el-form-item>
                <el-form-item label="附件" prop="uploadFile">
                  <file-view v-if="show" :limit="1" :type="typeSelect" :businessId="form.fileUpload"
                    :businessCode="businessCode" style="width: 500px"></file-view>
                </el-form-item>
              </el-form>
              <div class="dialog-footer" v-if="addSign !== 2" style="display: flex; justify-content: center;">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">关 闭</el-button>
              </div>
              <!--          题目-->
            </el-tab-pane>
            <el-tab-pane label="题目" name="second" v-if="addSign !== 0 && form.questionnaireType === '自定义'">
              <el-table :data="getRecordList">
                <el-table-column label="序号" type="index" :index="indexMethodRecord" />
                <el-table-column label="题目" align="center" prop="topicName" />
                <el-table-column label="题型" align="center" prop="questionType" />
                <el-table-column label="选项" align="center" prop="questionnaireAnswersItem" />
              </el-table>
              <pagination v-show="totalRecord > 0" :total="totalRecord" :page.sync="queryParamsRecord.pageNum"
                :limit.sync="queryParamsRecord.pageSize" @pagination="getTitleList" />
            </el-tab-pane>
          </el-tabs>

        </el-dialog>
        <select-user ref="select" :type="userType" :sign="sign" @ok="selectUser"></select-user>
        <el-dialog title="问卷调查" :visible.sync="openAnswer" width="700px" append-to-body v-if="openAnswer">
          <answer :questionnaireId="questionnaireId" @change="closeAnswer()"  :selectType="selectType" :height="'700px'"></answer>
        </el-dialog>
        <!--    附件展示对话框-->
        <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body v-if="openFileList">
          <UploadFile :upload-id="uploadId" :business-code="businessCode"></UploadFile>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="发起问卷" v-if="this.$store.state.user.info.companyType != '0' && enterpriseName == null">
        <questionnaire ></questionnaire>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { listByEnterpriseId, listInvestigation, getInvestigation, examineInvestigation, sendList, updateInvestigation, receptionList } from "@/api/questionnaire/investigation";
import { listType } from "@/api/maintype/type";
import MainType from "@/components/MainType/index"
import FileView from "@/components/FileView/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import BusinessInfo from "../../enterprise/info/index.vue";
import SelectUser from "../../system/role/selectUser.vue";
import Operate from "../../enterprise/businessinfo/operate.vue";
import { listTitle, getTitle, delTitle, addTitle, updateTitle } from "@/api/questionnaire/title";
import Investigation from "./index.vue";
import { getToken } from "../../../utils/auth";
import Answer from "./answer.vue";
import questionnaire from "../investigation/index"
import UploadFile from "../../upload/index.vue";
export default {
  name: "Training",
  props: {
    enterpriseId: {
      type: String,
      default: null
    },
    enterpriseName:{
      type: String,
      default: null
    },
    showClose: {
      type: Boolean,
      default: false
    },

  },
  computed: {
    Investigation() {
      return Investigation
    }
  },
  components: { UploadFile, Answer, Operate, SelectUser, BusinessInfo, Treeselect, MainType, FileView, questionnaire },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalRecord: 0,
      typeCode: 'investigation',
      // 活动信息培训表格数据
      trainingList: [],
      getRecordList: [],
      // 弹出层标题
      title: "",
      //详情状态
      ReadOnly: false,
      openAnswer: false,
      // 是否显示弹出层
      open: false,
      //判断对话框是否新增或编辑
      addSign: 0,
      //调用新增组件传递的题目id主键
      topicId: null,
      questionnaireId: null,//调用新增题目组件传递的问卷id主键
      //图片的标志位
      show: false,
      typeSelect: 0,
      selectType: 0,
      businessCode: 'investigation',
      //主分类
      options: null,
      userType: "1",
      uploadId: null,
      openFileList: false,
      sign: '1',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        questionnaireName: null,
        initStartTime: null,
        initEndTime: null
      },
      queryParamsRecord: {
        pageNum: 1,
        pageSize: 5,
        questionnaireId: null,
      },
      dialogImageUrl: null,
      ImgDig: false,
      //选显卡默认选中
      activeName: 'first',
      // 列信息
      columns: [
        { key: 0, label: `状态`, prop: "status", visible: true },
        { key: 1, label: `问卷名称`, prop: "questionnaireName", visible: true },
        { key: 2, label: `发起单位`, prop: "initiateUnits", visible: true },
        { key: 3, label: `发起时间`, prop: "initiateTime", visible: true },
        { key: 4, label: `联系人`, prop: "contacts", visible: true },
        { key: 5, label: `联系电话`, prop: "telephone", visible: true },
        { key: 6, label: `开始时间`, prop: "startTime", visible: true },
        { key: 7, label: `结束时间`, prop: "endTime", visible: true },
        { key: 8, label: `发送数量`, prop: "sendNum", visible: true },
        { key: 9, label: `回传数量`, prop: "returnNum", visible: true },
        { key: 10, label: `附件`, prop: "fileUrl", visible: true },
        { key: 11, label: `创建人`, prop: "creationName", visible: true },
        { key: 12, label: `创建时间`, prop: "creationTime", visible: true, },
        { key: 13, label: `作答人`, prop: "answerUser", visible: true },
      ],
      // 题目导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的题目数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/questionnaire/title/importData/"
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.listType();
    if (this.$route.query.id!==undefined){
      this.form.questionnaireId=this.$route.query.id;
     this.getQualificationDetail(this.form.questionnaireId);
     if (this.form.questionnaireType !== '第三方' && this.isCurrentTimeBeforeEndTime(this.form.startTime, this.form.endTime) && this.form.status !== '结束'){
       this.handleAnswer(this.form,0);
     }else {
       this.handleSelectAnswer(this.form,0);
     }
    }
    this.getList();
  },
  methods: {
    /** 查询活动信息培训列表 */
    getList() {
      this.loading = true;
      this.trainingList = [];
      //判断是否从客户跳转进来
      if (this.enterpriseName != "" && this.enterpriseName != null) {
        this.queryParams.receiverId = this.enterpriseId//用来暂存客户id
        listByEnterpriseId(this.queryParams).then(response => {
          this.trainingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        receptionList(this.queryParams).then(response => {
          this.trainingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }

    },
    //查询当前问卷详情数据
    getQualificationDetail(id){
      getInvestigation(id).then(res=>{
        this.form=res.data;
      })
    },
    //当当前时间大于结束时间
    isCurrentTimeBeforeEndTime(startTime, endTime) {
      const startDateTime = new Date(startTime);
      const endDateTime = new Date(endTime);
      const currentTime = new Date();
      return currentTime >= startDateTime && currentTime <= endDateTime;
    },
    //查询活动对应的题目列表
    getTitleList(questionnaireId) {
      this.queryParamsRecord.questionnaireId = questionnaireId;
      listTitle(this.queryParamsRecord).then(res => {
        console.log(res.rows)
        this.getRecordList = res.rows;
        this.getRecordList.map(function (record, index) {
          record.questionnaireAnswersItem = record.questionnaireAnswersList.map(function (item, index) {
            return (index + 1) + '.' + item.solutionName + ' ' + '(' + item.score + ')';
          }).join(" ");
        }).join("\n");

        this.totalRecord = res.totalRecord;
      })
    },
    //获取树节点数据
    listType() {
      listType({ typeCode: 'investigation' }).then(res => {
        console.log(res);
        this.options = res.data;
      })
    },
    selectUser(userId, userName) {
      this.$set(this.form, 'examineId', userId)
      this.$set(this.form, 'examineName', userName)
    },
    //关闭对话框
    closeTrain() {
      this.ReadOnly = false;
      this.show = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.show = false;
      this.reset();
    },
    selectOpen(type) {
      this.userType = 1;
      this.$refs.select.show();
    },
    parseUTCTime(time, format) {
      const date = new Date(time.replace('T', ' ').replace('+08', ''));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return format.replace('{y}', year).replace('{m}', month).replace('{d}', day).replace('{hh}', hours).replace('{mm}', minutes);
    },
    //获取当前用户在企业管理中的企业信息
    selectEnterprise(selection) {
      this.form.enterpriseId = selection.map(item => item.enterpriseId);
      this.form.receiverName = selection.map(item => item.enterpriseName).join(',');
      console.log(this.form)
      this.close()
    },
    // 表单重置
    reset() {
      this.form = {
        status: null,
        questionnaireId: null,
        questionnaireName: null,
        initiateUnits: null,
        initiateTime: null,
        validityTime: null,
        receiverId: null,
        receiverName: null,
        operateTime: null,
        operateId: null,
        operateName: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationId: null,
        creationName: null,
        creationTime: null,
        belongTo: null,
        classificationId: null,
        questionnaireType: null,
        contacts: null,
        telephone: null,
        startTime: null,
        endTime: null,
        examineId: null,
        examineName: null,
        fileUpload: null,
        //客户id数组
        enterpriseId: [],
        sendType: null,
        thirdPartyUrl: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.initStartTime = null;
      this.queryParams.initEndTime = null;
      this.handleQuery();
    },
    //树点击事件
    getNode(data, node, obj) {
      console.log(data)
      if (data.parentId != '00000000-0000-0000-0000-000000000000') {
        this.queryParams.classificationId = data.id
      } else {
        this.queryParams.classificationId = null
      }
      this.getList()
    },
    //当有值的时候，默认打开对话框为分类群发，没值为一键发送
    sendTrain() {
      if (this.form.receiverName !== null) {
        this.sendType = "groupSend"
      } else {
        this.sendType = "oneClick"
      }
    },
    //序号展示
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    indexMethodRecord(index) {
      return (this.queryParamsRecord.pageNum - 1) * this.queryParamsRecord.pageSize + index + 1;
    },
    //发送企业列表序号
    indexMethodSend(index) {
      return (this.sendParams.pageNum - 1) * this.sendParams.pageSize + index + 1;
    },
    /** 作答按钮 */
    handleAnswer(row, index) {
      this.selectType = 0;//是否是查看
      this.openAnswer = true;
      this.questionnaireId = row.questionnaireId || this.ids
    },
    /** 查看作答按钮操作 */
    handleSelectAnswer(row, index) {
      this.selectType = 1;
      this.openAnswer = true;
      this.questionnaireId = row.questionnaireId || this.ids
    },
    closeAnswer() {
      this.openAnswer = false;
      this.getList();
    },
    handleClick(url) {
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        // 如果没有协议，添加默认的http://协议
        url = 'http://' + url;
      } window.open(url, '_blank');
    },
    handlePictureCardPreview(id) {
      this.uploadId = id;
      this.openFileList = true;
    },
  }
};
</script>
<style scoped>
.hyperlink {
  color: #007BFF;
  /* 蓝色 */
  text-decoration: underline;
  cursor: pointer;
}
</style>
